use std::cell::RefCell;
use std::fs::File;
use std::io::Read;
use crate::class_path::class_file_packet::ClassFilePacket;


pub struct DirClassFilePacket {
    pub dir_path: RefCell<String>,
}


impl ClassFilePacket for DirClassFilePacket {
    fn read_class(&self, class_name: &String) -> Result<Vec<u8>, String> {
        let class_file_path = format!("{}/{}.class", self.dir_path.borrow(), class_name);
        let result = File::open(class_file_path);
        return match result {
            Ok(mut file) => {
                let mut data: Vec<u8> = Vec::new();
                let read_result = file.read_to_end(&mut data);
                return match read_result {
                    Ok(_size) => {
                        Ok(data)
                    }
                    Err(err) => {
                        Err(err.to_string())
                    }
                };
            }
            Err(message) => {
                Err(message.to_string())
            }
        };
    }

    fn to_string(&self) -> String {
        return format!("DirFileClassFilePacket[{}]", self.dir_path.borrow());
    }
}